package com.dctp.common.disruptor.close;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CloseOrderDisruptor {

    private static Disruptor<CloseOrderEvent> disruptor;
    private static RingBuffer<CloseOrderEvent> ringBuffer;

    public static void start() {
        int bufferSize = 1024 * 8; // RingBuffer 大小（必须是 2 的幂）
        ExecutorService executor = Executors.newSingleThreadExecutor();

        disruptor = new Disruptor<>(
                new CloseOrderEventFactory(),
                bufferSize,
                executor,
                ProducerType.MULTI, // 多生产者（多接口线程写入）
                new BlockingWaitStrategy()
        );

        disruptor.handleEventsWith(new CloseOrderEventHandler());
        disruptor.start();
        ringBuffer = disruptor.getRingBuffer();
    }

    /** ✅ 下单接口调用这里发布订单事件 */
    public static void publish(CloseOrder order) {
        long seq = ringBuffer.next();
        try {
            CloseOrderEvent event = ringBuffer.get(seq);
            event.setOrder(order);
        } finally {
            ringBuffer.publish(seq);
        }
    }

    public static void stop() {
        disruptor.shutdown();
    }
}
